package main

import (
	"fmt"
	"log"
	"syscall/js"
)

// func fib(i int) int {
// 	if i == 0 || i == 1 {
// 		return 1
// 	}
// 	return fib(i-1) + fib(i-2)
// }

// var (
// 	document = js.Global().Get("document")
// 	numEle   = document.Call("getElementById", "num")
// 	ansEle   = document.Call("getElementById", "ans")
// 	btnEle   = js.Global().Get("btn")
// )

//	func fibFunc(this js.Value, args []js.Value) interface{} {
//		v := numEle.Get("value")
//		if num, err := strconv.Atoi(v.String()); err == nil {
//			ansEle.Set("innerHTML", js.ValueOf(fib(num)))
//		}
//		return nil
//	}

var down = false

func etmousedown(this js.Value, args []js.Value) interface{} {
	fmt.Println("etmousedown")
	log.Println("fdsfdssdfsdfds")
	fmt.Println(args[0])
	var e = args[0]
	fmt.Println(e.Get("clientX").Float())
	fmt.Println(e.Get("clientY").Float())

	down = true
	return nil
}

func etmouseup(this js.Value, args []js.Value) interface{} {
	fmt.Println("etmouseup")
	fmt.Println(args[0])
	var e = args[0]
	fmt.Println(e.Get("clientX").Float())
	fmt.Println(e.Get("clientY").Float())
	down = false
	// testcall(100)
	// sum(this, args[0].Get("clientX").Int())
	return nil
}

func etmousemove(this js.Value, args []js.Value) interface{} {
	if down {
		fmt.Println("etmousemove")
		// fmt.Println(args[0])
		var e = args[0]
		fmt.Println(e.Get("clientX").Float())
		fmt.Println(e.Get("clientY").Float())
	}
	return nil
}

func begin() {
	fmt.Println("welcome")
	var document = js.Global().Get("document")
	var b = document.Get("body")
	b.Set("innerHTML", "<canvas id='main'></canvas>")
	var ce = document.Call("getElementById", "main")
	var width = document.Get("body").Get("clientWidth")
	var height = document.Get("body").Get("clientHeight")
	fmt.Println(width)
	fmt.Println(height)
	ce.Set("width", width)
	ce.Set("height", height)

	var ctx = ce.Call("getContext", "2d")
	ctx.Set("fillStyle", "#FF0000")
	ctx.Call("fillRect", 0, 0, width, height)

	ce.Call("addEventListener", "mousedown", js.FuncOf(etmousedown))
	ce.Call("addEventListener", "mouseup", js.FuncOf(etmouseup))
	ce.Call("addEventListener", "mousemove", js.FuncOf(etmousemove))
}
func sum(this js.Value, args []js.Value) interface{} {
	var sum int
	for _, val := range args {
		sum += val.Int()
	}
	println(sum)
	return sum
}

func main() {

	done := make(chan int, 0)
	js.Global().Set("sum", js.FuncOf(sum))
	var c = js.Global().Get("console")
	c.Call("log", "this is console.log message")
	c.Call("info", "this is console.info message")
	c.Call("error", "this is console.error message")
	begin()

	<-done
}
